// src/stores/application.ts
import { defineStore } from 'pinia'
import axios from '@/plugins/axios' // 确认路径正确
import { ElMessage } from 'element-plus'

// 物资申请数据接口 (对应后端的 MaterialApplicationDto)
export interface MaterialApplication {
  id: number
  materialId: number | null
  materialName: string | null
  quantity: number
  applyReason: string | null
  status: string // 待审核, 通过, 未通过
  applicantId: number | null
  applicantName: string | null
  reviewerId: number | null
  reviewerName: string | null
  reviewComments: string | null
  createTime: string | null // 假设后端返回格式化好的字符串或 ISO 字符串
  reviewTime: string | null // 假设后端返回格式化好的字符串或 ISO 字符串
}

// 创建申请的 Payload (对应 MaterialApplicationCreateRequest)
export interface ApplicationCreatePayload {
  materialId: number | null
  quantity: number | null
  applicantId: number | null // 管理员申请时需要指定员工ID
  applyReason?: string
}

// 更新申请的 Payload (对应 MaterialApplicationUpdateRequest)
export interface ApplicationUpdatePayload {
  id: number
  materialId: number | null
  quantity: number | null
  applyReason?: string
}

// 审核申请的 Payload (对应 MaterialApplicationReviewRequest)
export interface ApplicationReviewPayload {
  id: number
  reviewerId: number | null // 审核人 ID
  status: '通过' | '未通过' | string // 审核结果
  reviewComments?: string
}

export const useApplicationStore = defineStore('materialApplication', {
  state: () => ({
    applications: [] as MaterialApplication[],
    loading: false,
  }),
  actions: {
    // 获取物资申请列表
    async fetchApplications() {
      this.loading = true
      try {
        const response = await axios.get('/material-applications')
        if (response.data.code === 200 && Array.isArray(response.data.data)) {
          // 格式化日期时间
          this.applications = response.data.data.map((app: any) => ({
            ...app,
            createTime: app.createTime ? new Date(app.createTime).toLocaleString() : 'N/A',
            reviewTime: app.reviewTime ? new Date(app.reviewTime).toLocaleString() : null,
          }))
          return this.applications
        } else {
          throw new Error(response.data.message || '获取申请列表失败')
        }
      } catch (error: any) {
        console.error('获取申请列表失败:', error)
        ElMessage.error(error.message || '网络错误，无法获取申请列表')
        this.applications = [] // 出错时清空列表
        return []
      } finally {
        this.loading = false
      }
    },

    // 创建物资申请
    async createApplication(payload: ApplicationCreatePayload): Promise<MaterialApplication> {
      try {
        // 简单校验 payload
        if (!payload.materialId || !payload.quantity || payload.quantity <= 0 || !payload.applicantId) {
          throw new Error('物资、数量和申请人信息不完整')
        }
        const response = await axios.post('/material-applications', payload)
        if (response.data.code === 200) {
          await this.fetchApplications() // 创建成功后刷新列表
          return response.data.data
        } else {
          throw new Error(response.data.message || '创建申请失败')
        }
      } catch (error: any) {
        console.error('创建申请失败:', error)
        // 后端 BusinessException 会被全局处理器捕获，message 在 error.response.data.message
        const errMsg = error.response?.data?.message || error.message || '网络错误，无法创建申请'
        ElMessage.error(errMsg)
        throw new Error(errMsg) // 继续抛出错误，让调用处可以捕获
      }
    },

    // 更新物资申请 (只能更新待审核)
    async updateApplication(payload: ApplicationUpdatePayload): Promise<MaterialApplication> {
      try {
        if (!payload.id || !payload.materialId || !payload.quantity || payload.quantity <= 0) {
          throw new Error('ID、物资和数量不能为空')
        }
        const response = await axios.put('/material-applications', payload)
        if (response.data.code === 200) {
          await this.fetchApplications() // 更新成功后刷新列表
          return response.data.data
        } else {
          throw new Error(response.data.message || '更新申请失败')
        }
      } catch (error: any) {
        console.error('更新申请失败:', error)
        const errMsg = error.response?.data?.message || error.message || '网络错误，无法更新申请'
        ElMessage.error(errMsg)
        throw new Error(errMsg)
      }
    },

    // 审核物资申请
    async reviewApplication(payload: ApplicationReviewPayload): Promise<MaterialApplication> {
      try {
        if (!payload.id || !payload.reviewerId || !payload.status) {
          throw new Error('审核信息不完整')
        }
        const response = await axios.put('/material-applications/review', payload)
        if (response.data.code === 200) {
          await this.fetchApplications() // 审核成功后刷新列表
          return response.data.data
        } else {
          throw new Error(response.data.message || '审核申请失败')
        }
      } catch (error: any) {
        console.error('审核申请失败:', error)
        const errMsg = error.response?.data?.message || error.message || '网络错误，无法审核申请'
        ElMessage.error(errMsg)
        throw new Error(errMsg)
      }
    },

    // 删除物资申请
    async deleteApplication(id: number): Promise<void> {
      try {
        const response = await axios.delete(`/material-applications/${id}`)
        if (response.data.code === 200) {
          await this.fetchApplications() // 删除成功后刷新列表
          return // 无返回值表示成功
        } else {
          throw new Error(response.data.message || '删除申请失败')
        }
      } catch (error: any) {
        console.error('删除申请失败:', error)
        const errMsg = error.response?.data?.message || error.message || '网络错误，无法删除申请'
        ElMessage.error(errMsg)
        throw new Error(errMsg)
      }
    },
  },
})